package org.alex.samples.service;

import java.util.ArrayList;
import java.util.List;

import org.alex.samples.dao.IExamUserSubjectDAO;
import org.alex.samples.dao.ISubjectDAO;
import org.alex.samples.model.ExamSubjectVO;
import org.alex.samples.model.Subject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
public class SubjectServiceImp implements ISubjectService{
	
	@Autowired
	private ISubjectDAO subjectDAO; 
	
	@Autowired
	private IExamUserSubjectDAO examUserSubjectDAO;
	
	@Override
	public List<ExamSubjectVO> findAllSubject() {
		List<ExamSubjectVO> listvo = new ArrayList<ExamSubjectVO>();
		List<Subject> list = subjectDAO.findAllSubject();
		
		for(Subject subject:list){
			listvo.add(getSubjectById(subject.getSubId()));
		}
		
		return listvo;
	}

	@Override
	public void createSubject(ExamSubjectVO subjectVO) throws Exception {
		Subject subject = new Subject();
		BeanUtils.copyProperties(subjectVO,subject);
		
		subjectDAO.createSubject(subject);
	}

	@Override
	public ExamSubjectVO getSubjectById(Integer subId) {
		Subject extity = subjectDAO.getSubjectById(subId);
		if (extity != null) {
			ExamSubjectVO vo = new ExamSubjectVO();
			BeanUtils.copyProperties(extity, vo);
			return vo;
		}
		return null;
	}

	@Override
	public void editSubject(ExamSubjectVO subjectVO) throws Exception {
		Subject subject = new Subject();
		BeanUtils.copyProperties(subjectVO,subject);
		
		subjectDAO.editSubject(subject);
	}

	@Override
	public Integer deleteSubject(int subId) throws Exception {
		return subjectDAO.deleteSubject(subId);
	}

	@Override
	public void editSubjectStatus(Integer subId) {
		Subject subject = subjectDAO.getSubjectById(subId);
		if("0".equals(subject.getStatus())){
			subject.setStatus("1");
		}else{
			subject.setStatus("0");
		}
		try {
			subjectDAO.editSubject(subject);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public void delExamUserSubjectBySubId(Integer subId) {
		examUserSubjectDAO.delExamUserSubjectBySubId(subId);
	}

}
